$(function () {
    localStorage.clear();
    selectBill();
    /*提交*/
    $("#confirmClick").click(function(){
        if($(this).attr("first") == 1 &&　$(this).attr("second") == 1){
            secondPayAlert();
            return false;
        }
        if($(this).attr("first") == 1){
            firstPayAlert();
            return false;
        }
        if($("#sbmitInput").val() == 1){
            btn_Submit1();
        }else{
            btn_Submit2();
        }
    });
});

var type = null;
var user_bank_id = null;
var ub_phone = null;
var b_id = null;
var p_max_amt = "";
var p_min_amt = ""
var flag1 = null;
var flag2 = null;
var fund_type = null;
/*应付课程金额 默认为空*/
var p_set_amount = "";

var order_num = "";
var status = "";
var p_first = "";

/*判断是否能整除2，能整除就右浮动*/
function floatR(){
    var aLi = $(".ant-content ul li");
    for(var j=0; j< aLi .length; j++){
        if((j+1)%2==0){
            aLi[j].className='fr radius5';
        }
    }
}

/*获取地址栏的参数*/
function getQueryString(name) { 
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
      var r = window.location.search.substr(1).match(reg); 
      if (r != null) return decodeURI(r[2]); return null; 
}

/*四舍五入保留两位小数*/
function decimal(num,v){
    var vv = Math.pow(10,v);
    return Math.round(num*vv)/vv;
}

/*tab导航切换-----渲染数据*/
function tabChange(){
    $('.head-tab li').click(function(){
        var index = $(this).index()+1;
        $(this).addClass('cur').siblings().removeClass('cur');

        /*给隐藏域添加value*/
        $("#sbmitInput").val(index);
        
        /***判断点击的是信用卡账期,---1是银行账单，---2是信用卡***/
        if(index == 1){
            $(".change-bottom").remove();
            fund_type = 2;
            initEvent1();
            $(".ant-content1").addClass("cur1").removeClass("cur2");
        }else if(index == 2){
            $(".change-bottom").remove();
            /*渲染数据*/
            fund_type = 3;
            byStage2()
            $(".ant-content1").addClass("cur2").removeClass("cur1");
        }
    });
}

/*换卡选择*/
function change_bottom(){
    var html = '<p class="change-bottom text-center" onclick="showBankMask()">'
        html += ' <span class="color9" id="bankCard">付款</span>'
        html += '<a href="javascript:;" class="orange-color">(换卡)</a>'
        html += '</p>'
    $(html).appendTo($('.ant-bill'));
}

/*银行账单账期提交*/
// function btn_Submit1() {
//     /*课程id*/
//     //var p_id = getQueryString('p_id');
//     /*课程金额*/
//     var b_borrow_amount = $(".total").html();
//     /*期数*/
//     var b_period = $("#checkBill").val();
//     /*点击期数时把选择的期数放入缓存*/
//     //localStorage.setItem("b_period",b_period);

//     var datas = {
//         interface:'order@createOrder', 
//         "orderInfo":{
//             p_id:p_id,
//             b_borrow_amount: b_borrow_amount, 
//             b_period:b_period,
//         }
//     };
    
//     var p_min_amt = parseFloat($("#service_ame").attr("p_min_amt"));
//     var p_max_amt = parseFloat($("#service_ame").attr("p_max_amt"));
//     if (parseFloat(b_borrow_amount) <= 0) {
//         falert('请输入正确的课程金额');
//         return false;
//     } else if (parseFloat(b_borrow_amount) < p_min_amt) {
//         falert('课程金额不能低于最小额度（'+parseInt(p_min_amt)+'）');
//         return false;
//     } else if (parseFloat(b_borrow_amount) > p_max_amt) {
//         //$("#b_borrow_amount").val(p_max_amt);
//         falert('课程金额超出了最大额度（'+parseInt(p_max_amt)+'）');
//         return false;
//     }

//     common.ajax({
//         data: datas,
//         success: function (data) {
//             if (data.status == '2000') {
//                 window.location.href="/secoo/bind_card";
//             } else if (data.status == '5000') {
//                 falert(data.msg);
//             }
//         }
//     });
// }

/*信用卡账期提交*/
function btn_Submit2() {
    /*课程id*/
    var p_id = $("#checkBill").attr("p_id");
    /*课程金额*/
    var b_borrow_amount = $(".total").html();
    /*期数*/
    var b_period = $("#checkBill").val();
    /*点击期数时把选择的期数放入缓存*/
    localStorage.setItem("b_period",b_period);
    /*课程名称*/
    var p_name = $("#course_title").html()
    localStorage.setItem("p_name",p_name);
    /*type类型，用于判断是否首次绑卡*/
    localStorage.setItem("type",type);
    if(type == 1){/*已绑定过信用卡*/
        /*绑定的银行卡id*/
        localStorage.setItem("user_bank_id",user_bank_id);
        /*绑定过银行卡的手机号*/
        localStorage.setItem("ub_phone",ub_phone);
    }
    var datas = {
        interface:'order@createOrder', 
        "orderInfo":{
            p_id:p_id,
            b_borrow_amount: b_borrow_amount, 
            b_period:b_period,
            fund_type:fund_type
        }
    };
    
    if (parseFloat(b_borrow_amount) <= 0) {
        falert('请输入正确的课程金额');
        return false;
    } else if (parseFloat(b_borrow_amount) < p_min_amt) {
        falert('课程金额不能低于最小额度（'+parseInt(p_min_amt)+'）');
        return false;
    } else if (parseFloat(b_borrow_amount) > p_max_amt) {
        falert('课程金额超出了最大额度（'+parseInt(p_max_amt)+'）');
        return false;
    }

    common.ajax({
        data: datas,
        success: function (data) {
            if (data.status == '2000') {
                b_id = data.result.b_id;
                localStorage.setItem("b_id",b_id);
                if(type == 1){/*已绑定过信用卡*/
                    window.location.href="/secoo/pay_card";
                }else{
                    window.location.href="/secoo/bind_card";
                }
            } else if (data.status == '5000') {
                falert(data.msg);
            }
        }
    });
}

/*选择要账期的期数*/
function check_bill(){
    $(".ant-content ul li").click(function(){
        /*期数*/
        var b_period = $(this).find(".stageNum").html();
        /*课程id*/
        var p_id = $(this).attr("pid");
        $(".total").html(getQueryString('b_borrow_amount'));
        /*课程金额*/
        var b_borrow_amount = $(".total").html();
        /*费率*/
        var rate = $(this).find("#rate").html();

        // 账单总利息  chargeAmount (用户服务费)= 课程金额*用户费率/100*账期数
        chargeAmount = decimal(parseFloat(b_borrow_amount)*parseFloat(rate)/100*b_period,2)

        $("#checkBill").val(b_period);
        $("#checkBill").attr("p_id",p_id);
  
        /*最大金额最小金额赋值*/
        p_max_amt = parseFloat($(this).attr("p_max"));
        p_min_amt = parseFloat($(this).attr("p_min"));

        $(this).addClass('cur').siblings().removeClass('cur');
        selectProductDetail();
        
    })
}

/*银行账单账期--期数查询*/
// function initEvent1() {      
//     $("#tip").html('银行账单申请直接确认信息，若申请未通过，进入到申请入口选择其他账单方式');
//     var datas = {
//         interface:'Secoo@productBill',        
//     };
//     common.ajax({
//         data: datas,
//         success: function (data) {
//             if (data.status == '2000') {        
//                 /*先清空期数选择*/
//                 $("#bill_list").html("");    
//                 var list = data.result.rates;
//                 /*获取课程总金额*/
//                 var b_borrow_amount = $(".total").html();
//                 for(var i= 0;i<list.length;i++){
//                     var item = list[i];
//                     var bill_num = decimal(b_borrow_amount/item.stageNum,2);
//                     var html = '<li class="fl radius5">'
//                         html += '<h2>'+bill_num+'元X<span class="stageNum">'+ item.stageNum +'</span>期</h2>'
//                         html += '<p>费率<i id="rate">'+item.rate+'</i>%</p>'
//                         html += '</li>'
//                     $("#bill_list").append(html);
//                 }

//                 /*默认选中第一个*/
//                 $(".ant-content ul li:first-child").addClass("cur");
//                 check_bill();
//                 floatR();
//                 selectBank();
//                 change_bottom();
//                 /*应还总额=费率/100*应付课程金额+课程金额*/
//                 $("#total2").html(decimal(parseFloat(data.result.rates[0].rate)/100*parseFloat(b_borrow_amount)+parseFloat(b_borrow_amount),2));
//             } else if (data.status == '5000') {
//                 falert(data.msg);
//             }
//         }
//     });  
// }

/*隐藏信用卡类型*/
function hideBankMask(){
    $(".bank-mask").hide();
    $(".bank-layer").animate({"bottom":"-100%"})
}
/*显示信用卡类型*/
function showBankMask(){
    $(".bank-mask").show();
    $(".bank-layer").animate({"bottom":"0"})
}

/*查询绑定的信用卡列表*/
function selectBank() {  
    var datas = {
        interface:'Secoo@selectBank',        
    };

    common.ajax({
        data: datas,
        success: function (data) {
            if (data.status == '2000') {      
                var list = data.result;    
                $(".bank-layer ul").remove();   
                var html = '<ul>'
                for(var i= 0;i<list.length;i++){
                    var item = list[i];
                    var card_num = item.ub_card_no.substr(item.ub_card_no.length-4);  
                    html += '<li ub_phone="'+item.ub_phone+'" ub_id="'+item.ub_id+'">'+item.ub_bank_name+'('+card_num+')</li>'
                }
                html += '<li data-type="0">使用新卡支付</li></ul>'
                $(".bank-layer").append(html);

                var txt = list[0].ub_bank_name;
                var card_num = list[0].ub_card_no.substr(list[0].ub_card_no.length-4)
                $("#bankCard").html('使用'+txt+'('+card_num+')付款');
                ub_phone = list[0].ub_phone;

                /*选择信用卡*/
                $(".bank-layer li").click(function(){
                    var txt = $(this).html();
                    var dataType = $(this).attr("data-type");
                    if(dataType == 0){
                        type = 2;
                        $("#bankCard").html(txt);
                        btn_Submit2() 
                    }else{
                        ub_phone = $(this).attr("ub_phone");
                        $("#bankCard").html('使用'+txt+'付款');
                    }
                    $(this).addClass("cur").siblings().removeClass("cur");
                    hideBankMask()

                    user_bank_id = $(this).attr("ub_id");
                });
                type = 1;
                user_bank_id = list[0].ub_id;

            } else if (data.status == '5000') {
                type = 2;
                $(".change-bottom").remove();
            }
        }
    });  
}

/*查询判断是银行账单还是信用卡账期，还是两个都有*/
function selectBill() {  
    var datas = {
        interface:'Product@partnerFunds',   
    };

    common.ajax({
        data: datas,
        success: function (data) {
            if(data.status == '2000'){        
                var list = data.result;
                for(var i= 0;i<list.length;i++){
                    var item = list[i];
                    // 判断账单模式
                    if(item.fund_type == 2){ // 显示银行卡账期--储蓄卡账单
                        $(".dis-flex").hide();
                        $("#bank_title").show().html("持牌金融机构账单--储蓄卡");
                        $(".ant-bill").css("padding-top","0.729rem");
                        flag1 = 1;
                    }else if(item.fund_type == 3){ // 显示信用卡账期
                        $(".dis-flex").hide();
                        $("#bank_title").show().html("持牌金融机构账单--信用卡");
                        $(".ant-bill").css("padding-top","0.729rem");
                        flag2 = 1;
                    }

                    // 显示tab切换
                    if(flag1 == 1 && flag2 == 1){
                        $(".dis-flex").show();
                        $("#bank_title").hide()
                        $(".ant-bill").css("padding-top","0");
                    }
                }
                // 根据账单模式展示页面
                if(flag1 == 1 && flag2 == null){ // 银行
                    initEvent1();
                    $("#sbmitInput").val(1);
                    fund_type = 2;
                }else if(flag2 == 1 && flag1 == null){ // 信用卡
                    fund_type = 3;
                    byStage2()
                    $("#sbmitInput").val(2)
                }else if(flag1 == 1 && flag2 == 1){ // 银行 && 信用卡
                    initEvent1();
                    tabChange();
                    fund_type = 2;
                    $("#sbmitInput").val(1);
                    $(".ant-content1").addClass("cur1").removeClass("cur2");
                }
                selectBank()
                change_bottom();
            }else if(data.status == '5000'){
                falert(data.msg);
            }
        }
    });  
}

/*渲染机构可账期的期数----信用卡账期--期数查询 --- 新 */
function byStage2(){
    $("#tip").html('信用卡申请直接确认信息，若申请未通过，进入到申请入口选择其他账单方式');
    var p_name = getQueryString('p_name');
    var b_borrow_amount = getQueryString('b_borrow_amount');
    var datas = {
        interface:'product@getPeriodList',  
        p_name:p_name,
        fund_type:fund_type
    };
    /*课程名称*/
    $("#course_title").html(p_name);
    /*课程金额*/
    $(".total").html(b_borrow_amount);
    eidtPrice()
    common.ajax({
        data: datas,
        success: function (data) {
            if(data.status == '2000'){  
                /*先清空期数选择*/
                $("#bill_list").html("");    
                var list = data.result;
                
                for(var i=0;i<list.period.length;i++){
                    var item = list.period[i];

                    /*金额是否可修改*/
                    flog = item.p_amount_fixed;
                    if(flog == 0){
                        $("#price_box i").css("display","inline-block");
                    }

                    /*账期金额 = 应付金额 /期数*/
                    var bill_num = decimal(b_borrow_amount/item.p_period,2);

                    var html = '<li class="fl radius5" pid="'+item.p_id+'" p_max="'+item.p_max_amt+'" p_min="'+item.p_min_amt+'" down_payment="'+item.down_payment+'">'
                        html += '<h2>'+bill_num+'元X<span class="stageNum">'+ item.p_period +'</span>期</h2>'
                        html += '<p>费率<i id="rate">'+decimal(item.p_rate,2)+'</i>%</p>'
                        html += '</li>'
                    $("#bill_list").append(html);
                }
                floatR();
                /*默认选中第一个*/
                $(".ant-content ul li").each(function(){
                    if($(this).attr("down_payment") == 1){
                        $(this).addClass("cur").siblings().removeClass("cur");
                        /*最大和最小提交金额*/
                        p_max_amt = $(this).attr("p_max");
                        p_min_amt = $(this).attr("p_min");

                        /*期数*/
                        p_period = $(this).find(".stageNum").text();
                        /*课程id*/
                        p_id = $(this).attr("pid");

                    }else{
                        $(".ant-content ul li:first-child").addClass("cur");
                        /*最大和最小提交金额*/
                        p_max_amt = list.period[0].p_max_amt;
                        p_min_amt = list.period[0].p_min_amt;

                        /*期数*/
                        p_period = list.period[0].p_period;
                        /*课程id*/
                        p_id = list.period[0].p_id
                    }
                });

                /*机构名称*/
                $("#service_ame").html(list.partner_name);
                /*默认期数*/
                $("#checkBill").val(p_period);
                $("#checkBill").attr("p_id",p_id);
                selectProductDetail();
            
                // 账单总利息  chargeAmount (用户服务费)= 课程金额*用户费率/100*账期数
                chargeAmount = decimal(parseFloat(b_borrow_amount)*parseFloat(list.period[0].p_rate)/100*p_period,2)
               
                /*选择期数*/                
                check_bill();

            } else if (data.status == '5000') {
                falert(data.msg);
            }
        }
    });  
}
/*获取课程期数详情*/
function selectProductDetail() {  
    /*课程名称*/
    var p_name = getQueryString('p_name');
    /*期数*/
    var p_period = $("#checkBill").val();

    var datas = {
        interface:'Product@getProductDetail',  
        p_name:p_name,      
        p_period:p_period
    };

    common.ajax({
        data: datas,
        success: function (data) {
            if (data.status == '2000') {  
                var list = data.result;    
                for(var i= 0;i<list.length;i++){
                    var item = list[i];
                    firstPay();
                    p_set_amount = item.p_set_amount;


                    if(item.p_return_type == 1){
                        $("#installment").html("等额本息");
                    }else if(item.p_return_type == 2){
                        $("#installment").html("等本等息");
                    }else if(item.p_return_type == 3){
                        $("#installment").html("等额本金");
                    }else if(item.p_return_type == 4){
                        $("#installment").html("x+y模式");
                    }
                }
            } else if (data.status == '5000') {
                falert(data.msg);
            }
        }
    });  
}

/*查询是否有首付款*/
function firstPay(){
    /*课程id*/
    var p_id = $("#checkBill").attr("p_id");
    var datas = {
        interface:'Secoo@firstPayStatus',  
        p_id:p_id,
    };
    common.ajax({
        data: datas,
        success: function (data) {

            if(data.status == '2000'){
                //1000初始，2000成功，3000等待，4000失败,5000取消订单,6000疑账'
                if(data.result.status== "" || data.result.status == 1000){
                    if(!data.result.amount_real == 0){
                        $("#price_box i").css("display","none");
                        $("#firstPay").html("首付款¥"+formatMoney(data.result.amount_real,2));
                        $("#confirmClick").attr("first",1);
                        $(".change-bottom").hide();
                    }else{
                        $("#price_box i").css("display","inline-block");
                        $("#firstPay").html("");
                        $("#confirmClick").attr("first","");
                        $(".change-bottom").show();
                        $("#surplus").html("");
                    }

                }else if(data.result.status == 2000){
                    if(flog == 0){
                        $("#price_box i").css("display","inline-block");
                    }
                    $("#firstPay").html("首付款¥"+formatMoney(data.result.amount_real,2)+"（已付）");
                    $("#confirmClick").attr("first","");
                    $("#confirmClick").attr("second",1);
                    period = data.result.p_period;
                    $(".change-bottom").show();
                }
                
                totalPayable = p_set_amount-data.result.p_first_payment;
                first_payment = data.result.amount_real;
                order_num = data.result.order_num;
                status = data.result.status;
                p_first = data.result.p_first_payment;
                
                if(!data.result.amount_real == 0){
                    var surplushtml = "账单总利息：¥<span>"+ formatMoney(parseFloat(chargeAmount),2) +"</span><br>"+
                                        "剩余账单金额：¥<span>"+ formatMoney((p_set_amount-data.result.p_first_payment),2)+"</span><br>"+
                                        "应缴纳总额：¥<span>"+ formatMoney(p_set_amount*1+chargeAmount,2) +"</span>";
                    $("#surplus").html(surplushtml);
                    /*新增  账期金额= 剩余账单金额/期数  2018-12-25*/
                    surplus = p_set_amount-data.result.p_first_payment+chargeAmount;
                    for(var i=0;i<$("#bill_list li").length;i++){
                        var pried = $("#bill_list li").eq(i).find(".stageNum").html();  
                        var price = formatMoney(parseFloat(surplus)/pried,2);
                        $("#bill_list li").eq(i).find("h2").html(price+'元X<span class="stageNum">'+ pried +'</span>期');
                    }
                    /*新增 2018-12-25*/
                }

                /*应还总额=服务费+应付课程金额*/
                $("#total2").html(formatMoney(decimal(chargeAmount+parseFloat(totalPayable),2),2));
            } else if (data.status == '5003') {
                location.href = "pay/paylogin";
            } else if (data.status == '5000') {
                falert(data.msg);
            }
        }
    });  
}

function formatMoney(s, n)  
{  
   n = n > 0 && n <= 20 ? n : 2;  
   s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";  
   var l = s.split(".")[0].split("").reverse(),  
   r = s.split(".")[1];  
   t = "";  
   for(i = 0; i < l.length; i ++ )  
   {  
      t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");  
   }  
   return t.split("").reverse().join("") + "." + r;  
}

/*提交生成首付款订单*/
function subFirstPayOrder(){
    /*课程id*/
    var p_id = $("#checkBill").attr("p_id");
    var datas = {
        interface:'Secoo@firstPayOrder',  
        p_id:p_id,
        order_num:order_num,
        status:status
    };
    common.ajax({
        data: datas,
        success: function (data) {
            if(data.status == '2000'){  
                location.href=data.result.jumpUrl;
            } else if (data.status == '5000') {
                falert(data.msg);
            }
        }
    });  
}

//点击提交弹出遮罩层---未提交过首付的弹窗提示
function firstPayAlert() {
    layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        skin: 'yourclass',
        btn:['确认支付',"取消支付"],
        success:function(layero){
            layero.find('.layui-layer-btn').css('text-align', 'center');
        },
        shadeClose: false,
        area: ['82%', ''],
        content: '<h2>该课程需先支付首付款</h2><h3 class="orange-color">¥'+formatMoney(first_payment,2)+'</h3>',
        btn1: function(index, layero){
            subFirstPayOrder();
        }
    });
}
//点击提交弹出遮罩层---有提交过首付的弹窗提示
function secondPayAlert() {
    layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        skin: 'yourclass',
        btn:['确认支付',"取消支付"],
        success:function(layero){
            layero.find('.layui-layer-btn').css('text-align', 'center');
        },
        shadeClose: false,
        area: ['82%', ''],
        content: '<h2>您已经支付过该课程<span>'+period+'</span>期的首付款，是否支付所选账单期数的首付款</h2><h3 class="orange-color">¥'+formatMoney(first_payment,2)+'</h3>',
        btn1: function(index, layero){
            subFirstPayOrder();
        }
    });
}

/*修改金额弹窗*/
function eidtPrice(){
    $("#price_box i").click(function(){
        var obj = $(".total").html();
        layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            skin: 'yourclass',
            btn:['确认',"取消"],
            success:function(layero){
                layero.find('.layui-layer-btn').css('text-align', 'center');
            },
            shadeClose: false,
            area: ['82%', ''],
            content: '<p>修改金额</p><input type="number" class="radius5" id="price_input" value="'+obj+'"/>',
            btn1: function(index, layero){
                if($("#price_input").val()!=""){
                    var price = formatMoney($("#price_input").val(),2).replace(/,/g,'')
                    $(".total").html(price);
                    /*账期金额 = 应付金额 /期数*/
                    $("#bill_list li").each(function(){
                        var p_period = $(this).find(".stageNum").html();
                        var bill_num = decimal((price-p_first)/p_period,2);
                        $(this).find("h2").html(bill_num+'元X<span class="stageNum">'+ p_period +'</span>期');
                    });
                    /*判断首付款不为0*/
                    if(first_payment != 0){
                        var surplushtml = "账单总利息：¥<span>"+ formatMoney(parseFloat(chargeAmount),2) +"</span><br>"+
                                            "剩余账单金额：¥<span>"+ formatMoney((price-p_first),2)+"</span><br>"+
                                            "应缴纳总额：¥<span>"+ formatMoney(price*1+chargeAmount,2) +"</span>";
                        $("#surplus").html(surplushtml);
                    }

                    var totalPayable = price-p_first;
                    $("#total2").html(formatMoney(decimal(chargeAmount+parseFloat(totalPayable),2),2));    
                }
            }
        });

        $("#price_input").keyup(function(){
            $(this).val($(this).val().replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g,''));
        });
        $("#price_input").blur(function(){
            $(this).val($(this).val().replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g,''));
        });
    })
}